classdef fileWrapper_dev < handle
  % Wraps a Matlab file object w/ frequently-used data and methods
  % Derived from handle
  % Constructor signature: F = fileWrapper_dev(fileName, permissions), args required
  %
  % Author: David Goldsmith, Wash. State Dept. of Ecology, dgol461@ecy.wa.gov
  % Release date: N/A
    properties
        name;
        id;
        err={};
        permission;
    end
    
    methods
        function F = fileWrapper_dev(fileName, permissions)
            [F.id, tmp] = fopen(fileName, permissions);
            if isempty(tmp)
                F.name = regexprep(fileName, '\\\\', '\');
                F.permission = permissions;
            else
                F.appendErr(tmp)
            end
        end
        
        function checkedfprint(obj, s)
            if iscellstr(s), s = [s{:}]; end
            if ischar(s)
                s = regexprep(s, {'> +<'; '\t\t\t'; '\.  '},...
                                 {'>\r\n<'; '\r\n'; '\.\r\n\n'});
                check = numel(s);
                written = fprintf(obj.id, regexprep(s, '\', '\\\\'));
                if written ~= check
                    obj.appendErr(['Incomplete write to ' which(obj.name)])
                end
            else
                obj.appendErr(['Error writing to ' which(obj.name) ': '...
                               'argument was neither a char array nor a '...
                               'cell string array'])
            end
        end
        
        function appendErr(obj, msg)
            if ~isempty(msg)
                if isempty(obj.err)
                    obj.err = {msg};
                elseif ~strcmp(msg, obj.err)
                    obj.err = [obj.err msg];
                end
                if ~iscell(obj.err)
                    obj.err = {obj.err}; % obj.err should always be a cell array
                end
            end
        end
        
        function close(obj)
            if obj.isopen
                obj.appendErr(fclose(obj.id))
            end
        end
        
        function b = isopen(obj)
            try
                b = ftell(obj.id)~=-1;
            catch ME
                b = 0;
            end
        end
        
        function deleteFile(obj)
            if obj.isopen
                obj.close;
            end
            try
                delete(obj.name);
%                obj.delete;
            catch ME
                obj.appendErr(ME.message)
            end
        end
        
    end
    
end